package com.promise.jokerdream.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.promise.jokerdream.model.formation.FormationAttrModel
import com.promise.jokerdream.model.formation.FormationListItemModel
import com.promise.jokerdream.model.formation.FormationTypeModel
import com.promise.jokerdream.repository.GameApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

/**
 * 佣兵助阵ViewModel
 */
class FormationViewModel : ViewModel() {
    
    private val gameApi = GameApi.getInstance()
    
    // 助阵类型列表
    private val _formationTypes = MutableStateFlow<List<FormationTypeModel>>(emptyList())
    val formationTypes: StateFlow<List<FormationTypeModel>> = _formationTypes.asStateFlow()
    
    // 当前选择的助阵类型
    private val _selectedType = MutableStateFlow<FormationTypeModel?>(null)
    val selectedType: StateFlow<FormationTypeModel?> = _selectedType.asStateFlow()
    
    // 助阵组合列表
    private val _formations = MutableStateFlow<List<FormationListItemModel>>(emptyList())
    val formations: StateFlow<List<FormationListItemModel>> = _formations.asStateFlow()
    
    // 当前选择的助阵组合
    private val _selectedFormation = MutableStateFlow<FormationListItemModel?>(null)
    val selectedFormation: StateFlow<FormationListItemModel?> = _selectedFormation.asStateFlow()
    
    // 助阵属性列表
    private val _attrs = MutableStateFlow<List<FormationAttrModel>>(emptyList())
    val attrs: StateFlow<List<FormationAttrModel>> = _attrs.asStateFlow()
    
    // 当前选择的助阵属性
    private val _selectedAttr = MutableStateFlow<FormationAttrModel?>(null)
    val selectedAttr: StateFlow<FormationAttrModel?> = _selectedAttr.asStateFlow()
    
    // 加载状态
    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
    
    // 助阵类型加载状态
    private val _isLoadingTypes = MutableStateFlow(false)
    val isLoadingTypes: StateFlow<Boolean> = _isLoadingTypes.asStateFlow()
    
    // 助阵组合加载状态
    private val _isLoadingFormations = MutableStateFlow(false)
    val isLoadingFormations: StateFlow<Boolean> = _isLoadingFormations.asStateFlow()
    
    // 助阵属性加载状态
    private val _isLoadingAttrs = MutableStateFlow(false)
    val isLoadingAttrs: StateFlow<Boolean> = _isLoadingAttrs.asStateFlow()
    
    // 错误信息
    private val _errorMessage = MutableStateFlow<String?>(null)
    val errorMessage: StateFlow<String?> = _errorMessage.asStateFlow()
    
    // 缓存机制
    private val formationCache = mutableMapOf<Int, List<FormationListItemModel>>()
    private val attrCache = mutableMapOf<String, List<FormationAttrModel>>() // 使用 "typeId_index" 作为键
    
    // 当前失败的操作类型
    private var currentFailedOperation: String? = null
    
    init {
        loadFormationTypes()
    }
    
    /**
     * 手动重试
     */
    fun retry() {
        when (currentFailedOperation) {
            "loadFormationTypes" -> loadFormationTypes()
            "loadFormations" -> {
                val type = _selectedType.value
                if (type != null) {
                    loadFormations(type.id)
                }
            }
            "loadFormationAttrs" -> {
                val type = _selectedType.value
                val formation = _selectedFormation.value
                if (type != null && formation != null) {
                    val index = findFormationIndex(formation)
                    loadFormationAttrs(type.id, index)
                }
            }
        }
    }
    
    /**
     * 加载助阵类型列表
     */
    private fun loadFormationTypes() {
        viewModelScope.launch {
            _isLoadingTypes.value = true
            _errorMessage.value = null
            currentFailedOperation = "loadFormationTypes"
            
            try {
                val result = gameApi.queryFormationTypes()
                result.fold(
                    onSuccess = { response ->
                        if (response.result == 0) {
                            _formationTypes.value = response.formaitonType
                        } else {
                            _errorMessage.value = response.msg
                        }
                    },
                    onFailure = { exception ->
                        _errorMessage.value = exception.message ?: "加载助阵类型失败"
                    }
                )
            } catch (e: Exception) {
                _errorMessage.value = e.message ?: "加载助阵类型失败"
            } finally {
                _isLoadingTypes.value = false
            }
        }
    }
    
    /**
     * 选择助阵类型
     */
    fun selectType(type: FormationTypeModel) {
        _selectedType.value = type
        // 清空之前的选择和属性
        _selectedFormation.value = null
        _selectedAttr.value = null
        _attrs.value = emptyList()
        
        // 检查助阵组合缓存
        val cachedFormations = formationCache[type.id]
        
        if (cachedFormations != null) {
            // 使用缓存的助阵组合数据
            _formations.value = cachedFormations
        } else {
            // 加载数据
            loadFormations(type.id)
        }
    }
    
    /**
     * 加载助阵组合列表
     */
    private fun loadFormations(formationType: Int, index: Int = 0) {
        viewModelScope.launch {
            _isLoadingFormations.value = true
            _errorMessage.value = null
            currentFailedOperation = "loadFormations"
            
            try {
                val result = gameApi.queryFormationList(formationType, index)
                result.fold(
                    onSuccess = { response ->
                        if (response.result == 0) {
                            // 只更新助阵组合数据
                            _formations.value = response.formation
                            
                            // 缓存助阵组合数据
                            formationCache[formationType] = response.formation
                        } else {
                            _errorMessage.value = response.msg
                        }
                    },
                    onFailure = { exception ->
                        _errorMessage.value = exception.message ?: "加载助阵组合失败"
                    }
                )
            } catch (e: Exception) {
                _errorMessage.value = e.message ?: "加载助阵组合失败"
            } finally {
                _isLoadingFormations.value = false
            }
        }
    }
    
    /**
     * 选择助阵组合
     */
    fun selectFormation(formation: FormationListItemModel) {
        _selectedFormation.value = formation
        
        val type = _selectedType.value
        if (type != null) {
            val index = findFormationIndex(formation)
            val cacheKey = "${type.id}_$index"
            
            // 检查缓存
            val cachedAttrs = attrCache[cacheKey]
            if (cachedAttrs != null) {
                // 使用缓存数据
                _attrs.value = cachedAttrs
            } else {
                // 加载数据
                loadFormationAttrs(type.id, index)
            }
        }
    }
    
    /**
     * 加载助阵属性（单独方法）
     */
    private fun loadFormationAttrs(formationType: Int, index: Int = 0) {
        viewModelScope.launch {
            _isLoadingAttrs.value = true
            _errorMessage.value = null
            currentFailedOperation = "loadFormationAttrs"
            
            try {
                val result = gameApi.queryFormationList(formationType, index)
                result.fold(
                    onSuccess = { response ->
                        if (response.result == 0) {
                            // 更新数据
                            _attrs.value = response.attrInfo
                            
                            // 缓存数据，使用组合键
                            val cacheKey = "${formationType}_$index"
                            attrCache[cacheKey] = response.attrInfo
                        } else {
                            _errorMessage.value = response.msg
                        }
                    },
                    onFailure = { exception ->
                        _errorMessage.value = exception.message ?: "加载助阵属性失败"
                    }
                )
            } catch (e: Exception) {
                _errorMessage.value = e.message ?: "加载助阵属性失败"
            } finally {
                _isLoadingAttrs.value = false
            }
        }
    }
    
    /**
     * 只刷新助阵组合列表（不刷新助阵类型）
     */
    private fun refreshFormationsOnly() {
        val type = _selectedType.value
        val formation = _selectedFormation.value
        if (type != null) {
            val index = formation?.let { findFormationIndex(it) } ?: 0
            loadFormations(type.id, index)
        }
    }
    
    /**
     * 只刷新助阵类型列表
     */
    fun refreshFormationTypes() {
        loadFormationTypes()
    }
    
    /**
     * 只刷新助阵属性列表（不刷新助阵组合）
     */
    private fun refreshAttrsOnly() {
        val type = _selectedType.value
        val formation = _selectedFormation.value
        if (type != null) {
            val index = formation?.let { findFormationIndex(it) } ?: 0
            loadFormationAttrs(type.id, index)
        }
    }
    
    /**
     * 选择助阵属性
     */
    fun selectAttr(attr: FormationAttrModel) {
        _selectedAttr.value = attr
    }
    
    /**
     * 查找助阵组合在列表中的索引
     */
    private fun findFormationIndex(formation: FormationListItemModel): Int {
        return _formations.value.indexOfFirst { it.id == formation.id }.takeIf { it >= 0 } ?: 0
    }
    
    /**
     * 激活助阵
     */
    fun activateFormation() {
        val type = _selectedType.value
        val formation = _selectedFormation.value
        
        if (type != null && formation != null) {
            viewModelScope.launch {
                _isLoading.value = true
                _errorMessage.value = null
                
                try {
                    val result = gameApi.activateFormation(type.id, formation.id)
                    result.fold(
                        onSuccess = { response ->
                            if (response.result == 0) {
                                // 激活成功，只刷新助阵组合列表
                                refreshFormationsOnly()
                            } else {
                                _errorMessage.value = response.msg
                            }
                        },
                        onFailure = { exception ->
                            _errorMessage.value = exception.message ?: "激活助阵失败"
                        }
                    )
                } catch (e: Exception) {
                    _errorMessage.value = e.message ?: "激活助阵失败"
                } finally {
                    _isLoading.value = false
                }
            }
        }
    }
    
    
    /**
     * 清除错误信息
     */
    fun clearError() {
        _errorMessage.value = null
    }
    
    /**
     * 重置选择
     */
    fun resetSelection() {
        _selectedType.value = null
        _selectedFormation.value = null
        _selectedAttr.value = null
        _formations.value = emptyList()
        _attrs.value = emptyList()
    }
}
